package bargain.server.service.impl;

import bargain.enitity.Account;
import bargain.enitity.FreezeAssets;
import bargain.server.dao.AccountDao;
import bargain.server.dao.FreezeAssetsDao;
import bargain.service.BService;
import org.apache.dubbo.config.annotation.DubboService;
import org.dromara.hmily.annotation.HmilyTCC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @ClassName AServiceImpl
 * @Description
 * @Author Jingxiao.Ye
 * @Date 2022/1/4 下午9:46
 * @Version V1.0
 * @Since JDK 11
 */
@DubboService
@Service
public class BServiceImpl implements BService {

    @Autowired
    private AccountDao accountDao;

    @Autowired
    private FreezeAssetsDao freezeAssetsDao;

    @Override
    @HmilyTCC(confirmMethod = "successTransferAccount", cancelMethod = "failTransferAccount")
    public void transferAccount(long tranId, long accountId, BigDecimal dollar, BigDecimal rmb) {
        Account account = new Account();
        account.setDollar(BigDecimal.valueOf(0));
        account.setRmb(rmb);
        account.setId(accountId);
        int i = accountDao.reduceRmb(account);
        if (i > 0) {
            FreezeAssets freezeAssets = new FreezeAssets();
            freezeAssets.setCreateTime(System.currentTimeMillis());
            freezeAssets.setDollar(BigDecimal.valueOf(0));
            freezeAssets.setRmb(rmb);
            freezeAssets.setAccountId(accountId);
            freezeAssets.setId(tranId);
            freezeAssetsDao.save(freezeAssets);
        } else {
            throw new RuntimeException("余额不足");
        }
    }

    @Transactional
    public void successTransferAccount(long tranId, long accountId, BigDecimal dollar, BigDecimal rmb) {
        int del = freezeAssetsDao.del(tranId);
        if(del > 0){
            Account account = new Account();
            account.setDollar(dollar);
            account.setId(accountId);
            accountDao.addDollar(account);
        }
    }

    @Transactional
    public void failTransferAccount(long tranId, long accountId, BigDecimal dollar, BigDecimal rmb) {
        int del = freezeAssetsDao.del(tranId);
        if(del > 0){
            Account account = new Account();
            account.setRmb(rmb);
            account.setId(accountId);
            accountDao.addRmb(account);
        }
    }
}
